//
//  HomeViewController.m
//  Tunnel
//
//  Created by wbb on 2022/3/8.
//

#import "HomeViewController.h"
#import "HomeCell1.h"
#import "HomeCell2.h"
#import "HomeCell3.h"
#import "HomeCell4.h"
#import "HomeCell5.h"
#import "HomeCell6.h"
#import "HomeCell7.h"
#import "HomeCell8.h"
#import "YXJCVC.h"
#import "JKGJVC.h"
#import "JKGJDetailVC.h"
#import "GZGJVC.h"
#import "YJXYVC.h"
#import "AQJCVC.h"
#import "SPJKVC.h"
@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UILabel * titleLab;
@property (nonatomic, strong) UIImageView * bgImgView;
@property (nonatomic, strong) NSDictionary * dataDic;
@property (nonatomic, copy) NSArray * countDtos;
@property (nonatomic, copy) NSDictionary * monthDic;
@property (nonatomic, copy) NSArray * devcieTypeCountList;
@property (nonatomic, copy) NSDictionary * yjtjDic;

@property (nonatomic, copy) NSString * selectItem;
@property (nonatomic, copy) NSString * selectItem3;
@property (nonatomic, copy) NSArray * systemDictionaryList;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"首页";
    
    
    [self initUI];
    
    [self getHomeRequestData];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    [delegate getUnReadNum];
    
    
    kWEAK_SELF
    [TYNetWorkTool getRequest:TYGetDeptCount parameters:@{} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        weakSelf.countDtos = [NSArray arrayWithArray:data[@"data"][@"countDtos"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:6 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

        });
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
    }];
}

- (void)getHomeRequestData{
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    kWEAK_SELF;
    [TYNetWorkTool postRequest:TYDevcieStatusCount parameters:@{@"sysType":@""} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        NSLog(@"-------1111-----------");
        if(success) {
            weakSelf.dataDic = [NSDictionary dictionaryWithDictionary:data[@"data"]];
            
        }
        
        
        
        dispatch_group_leave(group);
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        dispatch_group_leave(group);
        
        
    }];
    //    dispatch_group_enter(group);
    //    [TYNetWorkTool postRequest:TYDevcieTypeCount parameters:@{@"sysType":@""} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
    //        // 进入DispatchGroup，表示开始一个任务
    //
    //        weakSelf.devcieTypeCountList = [NSArray arrayWithArray:data[@"data"]];
    //        dispatch_group_leave(group);
    //
    //        NSLog(@"-------222-----------");
    //
    //    } failureBlock:^(NSString * _Nonnull description) {
    //        // 进入DispatchGroup，表示开始一个任务
    //        dispatch_group_leave(group);
    //
    //    }];
    
    
    
    dispatch_group_enter(group);
    [TYNetWorkTool getRequest:TYGetDeptCount parameters:@{} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        weakSelf.countDtos = [NSArray arrayWithArray:data[@"data"][@"countDtos"]];
        dispatch_group_leave(group);
        
        NSLog(@"-------333-----------");
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        dispatch_group_leave(group);
        
    }];
    
    
    NSInteger currentYear = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:[NSDate date]].year;
    NSArray<NSString *> *currentRange = [TYGlobal timeRange:currentYear];
    
    // 输出当前年份结果（截止到当月）
    if (currentRange) {
        NSString *start = currentRange[0];
        NSString *end = currentRange[1];
        
        [self yjtjRequestData:group startTime:start endTime:end];
        [self nhtjRequestData:group startTime:start endTime:end];
        
    }
    
    // 设备数量
    [self devcieTypeCount:group sysType:@""];

    
    // 所有任务完成后的回调（在主线程执行，因为要更新UI）
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"-------ui-----------");
        [self.tableView reloadData];
    });
    
    
    // 设备类型
    [TYNetWorkTool postRequest:TYPostSystemDictionaryList
                    parameters:@{@"levelType":@"巡检",@"planDictionaryId":@"6",@"proId":@"1"}
                  successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.systemDictionaryList = data[@"data"];
        
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}
- (void)devcieTypeCount:(dispatch_group_t)group sysType:(NSString *)sysType {
    if(group){
        dispatch_group_enter(group);
        
    }
    kWEAK_SELF;
    [TYNetWorkTool postRequest:TYDevcieTypeCount parameters:@{@"sysType":sysType?:@""} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        
        weakSelf.devcieTypeCountList = [NSArray arrayWithArray:data[@"data"]];
        if(group){
            dispatch_group_leave(group);
            
        }else {
            
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
        }
        
        NSLog(@"-------222-----------");
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        if(group){
            dispatch_group_leave(group);
            
        }
        
    }];
}
- (void)yjtjRequestData:(dispatch_group_t)group startTime:(NSString *)startTime endTime:(NSString *)endTime {
    if(group){
        dispatch_group_enter(group);
        
    }
    kWEAK_SELF
    [TYNetWorkTool postRequest:TYQueryMonthCount parameters:@{
        @"endTime": endTime?:@"",
        @"startTime": startTime?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        weakSelf.yjtjDic = [NSDictionary dictionaryWithDictionary:data[@"data"]];
        
        if(group){
            dispatch_group_leave(group);
        }else {
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        NSLog(@"-------444-----------");
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        if(group){
            dispatch_group_leave(group);
        }
        
    }];
}
- (void)nhtjRequestData:(dispatch_group_t)group startTime:(NSString *)startTime endTime:(NSString *)endTime {
    if(group){
        dispatch_group_enter(group);
        
    }
    kWEAK_SELF
    [TYNetWorkTool postRequest:TYGetElectricityConsumption parameters:@{
        @"endTime": endTime?:@"",
        @"startTime": startTime?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        // 进入DispatchGroup，表示开始一个任务
        weakSelf.monthDic = [NSDictionary dictionaryWithDictionary:data[@"data"]];
        
        
        if(group){
            dispatch_group_leave(group);
        }else {
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:7 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        NSLog(@"-------5555-----------");
        
    } failureBlock:^(NSString * _Nonnull description) {
        // 进入DispatchGroup，表示开始一个任务
        if(group){
            dispatch_group_leave(group);
        }
        
    }];
}
- (void)initUI {
    
    self.view.backgroundColor = hexColor(F6F7F9);
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    self.tableView.contentInset = UIEdgeInsetsMake(kStatusBarHeight + 122, 0, 0, 0);
    
   
    
    [self.tableView addSubview:self.bgImgView];
    self.tableView.clipsToBounds = NO;

    [self.tableView sendSubviewToBack:self.bgImgView];
    [self.tableView insertSubview:self.bgImgView atIndex:0];
    self.bgImgView.layer.zPosition = -1;
    
}

- (UIImageView *)bgImgView {
    if(!_bgImgView) {
        UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kStatusBarHeight - 122-70, kSCREEN_WIDTH, kSCREEN_WIDTH * 278.f/375)];
        bgImgView.image = [UIImage imageNamed:@"home_bg_img"];
       _bgImgView = bgImgView;
       
        
       

        
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        [bgImgView addSubview:label];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"高浪路智慧隧道管控平台" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize: 22 weight:UIFontWeightBold],NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]}];
        label.attributedText = string;
        self.titleLab = label;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.top.equalTo(bgImgView.mas_top).offset(94);
        }];
        
        
        UILabel *label1 = [[UILabel alloc] init];
        label1.numberOfLines = 0;
        [bgImgView addSubview:label1];
        NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc] initWithString:@"BIM隧道|数字孪生|无纸办公" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0]}];
        label1.attributedText = string1;
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.top.equalTo(label.mas_bottom).offset(10);
        }];
        
    }
    return _bgImgView;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSLog(@"%f",self.view.safeAreaInsets.top);
//    [self.titleLab mas_remakeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.offset(0);
//        make.top.equalTo(self.view.mas_top).offset(49+self.view.safeAreaInsets.top);
//    }];
    
//    self.bgImgView.frame =CGRectMake(0, -kStatusBarHeight - 122 - 50, kSCREEN_WIDTH, kSCREEN_WIDTH * 278.f/375);
}

- (void)pushVc:(NSInteger)index {
    switch (index) {
        case 0:
        {
            YXJCVC *vc = [[YXJCVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        case 1:
        {
            JKGJVC *vc = [[JKGJVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        case 2:
        {
            GZGJVC *vc = [[GZGJVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        case 3:
        {
            YJXYVC *vc = [[YJXYVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        case 4:
        {
            AQJCVC *vc = [[AQJCVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        case 5:
        {
            SPJKVC *vc = [[SPJKVC alloc] init];
            [self.navigationController pushViewController:vc animated:NO];
        }
            break;
        default:
            break;
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource ----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row == 0) {
        return ScaleNum(140) ;
    }
    if(indexPath.row == 1) {
        return ScaleNum(120) ;
    }
    if(indexPath.row == 2) {
        return ScaleNum(237) ;
    }
    if(indexPath.row == 3) {
        NSArray *offLineDeviceList = [NSArray arrayWithArray:self.dataDic[@"offLineDeviceList"]];
        NSInteger h1 =  offLineDeviceList.count > 0 ? (offLineDeviceList.count * 53) : 60;
        NSInteger height = ScaleNum(118 + h1);
        return height;
    }
    
    if(indexPath.row == 4) {
        NSArray *alarmDeviceList = [NSArray arrayWithArray:self.dataDic[@"alarmDeviceList"]];
        NSInteger h1 =  alarmDeviceList.count > 0 ? (alarmDeviceList.count * 53) : 60;
        return ScaleNum(180 + h1);
    }
    if(indexPath.row == 5) {
        return ScaleNum(240) ;
    }
    if(indexPath.row == 6) {
        return ScaleNum(240) ;
    }
    if(indexPath.row == 7) {
        return ScaleNum(240) ;
    }
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.row == 0){
        HomeCell1 *cell1 = [[HomeCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
        kWEAK_SELF;
        cell1.ty_selectForIndex = ^(NSInteger index) {
            [weakSelf pushVc:index];
        };
        return cell1;
        
    }
    
    if(indexPath.row == 1){
        HomeCell2 *cell2 = (HomeCell2 *)[HomeCell2 nibCell];
        [cell2 cellWithData:self.dataDic?:@{}];
        return cell2;
        
    }
    if(indexPath.row == 2){
        HomeCell3 *cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        if(!cell3){
            cell3 = (HomeCell3 *)[HomeCell3 nibCell];
        }
        cell3.systemDictionaryList = self.systemDictionaryList;
        cell3.selectItem3 = self.selectItem3;
        [cell3 cellWithData:self.devcieTypeCountList];
        
        kWEAK_SELF;
        cell3.cellBlock3 = ^(NSString * _Nonnull selectItem) {
            weakSelf.selectItem3 = selectItem;
            [weakSelf devcieTypeCount:nil sysType:selectItem];
            
        };
        return cell3;
    }
    
    if(indexPath.row == 3){
        HomeCell4 *cell4 = (HomeCell4 *)[HomeCell4 nibCell];
        [cell4 cellWithData:self.dataDic?:@{}];
        
        return cell4;
    }
    
    if(indexPath.row == 4){
        HomeCell5 *cell5 = (HomeCell5 *)[HomeCell5 nibCell];
        [cell5 cellWithData:self.dataDic?:@{}];
        cell5.callBack = ^(NSDictionary * _Nonnull dict) {
            JKGJDetailVC * vc = [JKGJDetailVC new];
            vc.jkId = dict[@"alarmId"];
            [self.navigationController pushViewController:vc animated:true];
        };
        return cell5;
    }
    
    if(indexPath.row == 5){
        HomeCell6 *cell6 = (HomeCell6 *)[HomeCell6 nibCell];
        [cell6 cellWithData:self.yjtjDic?:@{}];
        return cell6;
    }
    
    if(indexPath.row == 6){
        HomeCell7 *cell7 = [tableView dequeueReusableCellWithIdentifier:@"cell7"];
        if(!cell7){
            cell7 = (HomeCell7 *)[HomeCell7 nibCell];
        }
        [cell7 cellWithData:self.countDtos?:@[]];
        
        return cell7;
    }
    if(indexPath.row == 7){
        HomeCell8 *cell8 = [tableView dequeueReusableCellWithIdentifier:@"cell8"];
        if(!cell8){
            cell8 = (HomeCell8 *)[HomeCell8 nibCell];
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.monthDic?:@{}];
        dic[@"selectItem"] = self.selectItem;
        [cell8 cellWithData:dic];
        kWEAK_SELF;
        cell8.cellBlock = ^(NSArray * _Nonnull range,NSString *selectItem) {
            weakSelf.selectItem = selectItem;
            [weakSelf nhtjRequestData:nil startTime:range[0] endTime:range[1]];
        };
        return cell8;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
}


#pragma mark ---- lazy ----
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"HomeCell8" bundle:nil] forCellReuseIdentifier:@"cell8"];
    }
    return _tableView;
}

@end

